package com.zxlspace.weixinseller.service.impl;

import com.zxlspace.weixinseller.DTO.OrderDTO;
import com.zxlspace.weixinseller.enums.ResultEnum;
import com.zxlspace.weixinseller.exception.SellException;
import com.zxlspace.weixinseller.service.BuyerService;
import com.zxlspace.weixinseller.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author zhangxiaolin@zhonhajt.com
 * @Title: 买家订单业务实现类
 * @Package com.zxlspace.weixinseller.service.impl
 * @Description:
 * @date 2018/6/22 15:52
 */
@Service
@Slf4j
public class BuyerServiceImpl implements BuyerService {
    @Autowired
    private OrderServiceImpl orderService;

    @Override
    public OrderDTO findOrderOne(String openid, String orderId) {
        return checkOrderOwner(openid, orderId);
    }

    @Override
    public OrderDTO cancelOrder(String openid, String orderId) {
        OrderDTO orderDTO = checkOrderOwner(openid, orderId);
        if (orderDTO == null) {
            log.error("【取消订单】查不到该订单, orderId={}", orderId);
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }
        return orderService.cancelOrder(orderDTO);
    }

    /**
     * 检查当前订单id和openid是否匹配
     * @param openid
     * @param orderId
     * @return
     */
    private OrderDTO checkOrderOwner(String openid, String orderId) {
        OrderDTO orderDTO = orderService.findOne(orderId);
        if (orderDTO == null) {
            return null;
        }

        if (!orderDTO.getBuyerOpenId().equalsIgnoreCase(openid)) {
            log.error("【查询订单】订单的openid不一致， openid={}, orderDTO={}", openid, orderDTO);
            throw new SellException(ResultEnum.ORDER_OWNER_ERROR);
        }
        return orderDTO;
    }
}
